package com.abacus.pay.dao;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.Transaction;

public final class TransactionStrategy {
	private static TransactionStrategy transactionStrategy;
	private final static Map<Thread, Transaction> transactionMap = new HashMap<Thread, Transaction>();
	private final static Map<Thread, Calendar> calendarMap = new HashMap<Thread, Calendar>();

	private TransactionStrategy() {
		super();
	}

	public static TransactionStrategy getInstance() {
		if (null == transactionStrategy) {
			transactionStrategy = new TransactionStrategy();
		}
		return transactionStrategy;
	}

	public void begin() {
		Transaction transaction = transactionMap.get(Thread.currentThread());
		if (null != transaction) {
			transaction.begin();
			calendarMap.put(Thread.currentThread(), Calendar.getInstance());
		} else {
			transaction = HibernateUtil.getCurrentSession().beginTransaction();
			transactionMap.put(Thread.currentThread(), transaction);
			calendarMap.put(Thread.currentThread(), Calendar.getInstance());
		}
	}

	public void commit() {
		Transaction transaction = transactionMap.get(Thread.currentThread());
		Calendar calendar = calendarMap.get(Thread.currentThread());
		if (null != transaction) {
			if (null != calendar) {
				long time = Calendar.getInstance().getTimeInMillis() - calendar.getTimeInMillis();
			}
			transaction.commit();
			transactionMap.remove(Thread.currentThread());
			calendarMap.remove(Thread.currentThread());
		} else {
		}
	}

	public void rollback() {
		Transaction transaction = transactionMap.get(Thread.currentThread());
		Calendar calendar = calendarMap.get(Thread.currentThread());
		if (null != transaction && transaction.isActive()) {
			if (null != calendar) {
				long time = Calendar.getInstance().getTimeInMillis() - calendar.getTimeInMillis();
			}
			transaction.rollback();
			transactionMap.remove(Thread.currentThread());
			calendarMap.remove(Thread.currentThread());
		} else {
		}
	}

	public void clearCache() {
		Session session = HibernateUtil.getCurrentSession();
		if (session != null) {
			session.flush();
			session.clear();
		}
	}
}
